import { AxiosRequestConfig } from 'axios';
import { SketionRequestOptions } from 'sketion-http';
import { isArray, isObject } from '@/utils/is';

// export type MyRequest = SketionRequestOptions & AxiosRequestConfig

export interface MyRequest extends SketionRequestOptions, AxiosRequestConfig {
  loadingText?: string;
  showLoading?: boolean;
  showError?: boolean;
  showWarn?: boolean;
  needCache?: boolean;
  authenticationScheme?: string;
  successText?: string;
}

export interface FormError {
  field: string;
  error: string;
}
export interface StandardResponse<T = any> {
  code: number;
  msg: string;
  data: T;
  $originalData: any;
  summary?: {
    encrypted: number;
    keyId: string;
  };
  secretData?: string;
  page?: number;
  total?: number;
  pageSize?: number;
}

export interface PageData<T = any> {
  totalRecords: number;
  pageSize: number;
  pageNum: number;
  pageData: T[];
}

export class MyResponse<T = any> implements StandardResponse<T> {
  code: number;

  msg: string;

  data: T;

  $originalData: any;

  total?: number;

  pageSize?: number;

  page?: number;

  summary?: {
    encrypted: number;
    keyId: string;
  };

  secretData?: string;

  constructor(res: StandardResponse) {
    this.code = res.code;
    this.msg = res.msg;
    this.data = res.data;
    this.$originalData = res.$originalData;
    this.summary = res.summary;
    this.secretData = res.secretData;
    this.page = res.page;
    this.total = res.total;
    this.pageSize = res.pageSize;
  }

  public get isLoading() {
    return this.code === -1000;
  }

  public get success() {
    return this.code === 0 || this.code === 200;
  }

  public setEmpty(): MyResponse<T> {
    this.data = null as any;
    return this;
  }

  public setError(err: string): MyResponse<T> {
    this.code = 500;
    this.msg = err;
    return this;
  }

  public setLoading(data?: any): MyResponse<T> {
    this.code = -1000;
    if (data !== undefined) {
      this.data = data;
    }
    return this;
  }

  public get isLocalError() {
    return this.code >= 5000;
  }

  public update(res: StandardResponse): MyResponse<T> {
    this.code = res.code;
    this.msg = res.msg;
    this.data = res.data;
    this.$originalData = res.$originalData;
    return this;
  }

  public setSuccess(data?: any): MyResponse<T> {
    this.code = 0;
    this.data = data;
    return this;
  }

  public get isEmpty() {
    if (!this.success) {
      return false;
    }
    if (!this.data) {
      return true;
    }
    if (isArray(this.data) && this.data instanceof Array) {
      if (this.data.length === 0) {
        return true;
      }
    }

    // @ts-ignore
    if (isObject(this.data) && isArray(this.data.records)) {
      // @ts-ignore
      if (this.data.records.length === 0) {
        return true;
      }
    }

    return false;
  }
}

export type TypeParams = Record<string, any>;
